package com.sis.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sis.constant.MergeFileConstants;
import com.sis.db.DataSource;


public class MergeFileService {
	
	private List<String> listHeader ;
	private FileWriter writer = null;
	private BufferedWriter buffer = null;
	private BufferedReader br = null ;
	
	DataSource dataSource;
	StringBuilder str = new StringBuilder();
	
	public void readBaseFile(String username) throws Exception{

		
		try{
			
			br = new BufferedReader(new FileReader(System.getProperty("pInput").toString()));
			Map<String, String> mapRow = new HashMap<>();
			String line ;
			line = br.readLine();
			int indexSKU = 0;
			if(line != null){
				listHeader = new ArrayList<>();
				line = line.substring(1,line.length()-1);
				String[] key = line.split(MergeFileConstants.SPLIT);
				
				for(int i = 0; i < key.length ; i++){
					listHeader.add(key[i].toUpperCase());
					mapRow.put(key[i].toUpperCase(), key[i].toUpperCase());
					if(key[i].contentEquals(MergeFileConstants.SKU)){
						indexSKU=i;
					}
				}
				
				writeFile(mapRow,false);
			}
			
			List<String> listArg = new ArrayList<>();
			
			dataSource.executeBate(MergeFileConstants.DELETEINTERFACE);
			
			StringBuilder sqlCommand = new StringBuilder();
			sqlCommand.append(MergeFileConstants.INSERTINTERFACE);
			int index = 0;
	        while ((line = br.readLine()) != null) {
	        	
	        	mapRow.clear();
	        	index = 0;
	        	String[] column = line.split(MergeFileConstants.SPLIT);
	        	column[index] = column[index].substring(1,column[index].length());
	        	column[column.length-1] = column[column.length-1].substring(0,column[column.length-1].length()-1);
	        	
	        	for(String k : listHeader){
	        		mapRow.put(k, column[index]);	        		
	        		index++;
	        	}
	        	
	        	sqlCommand.append(" ('");
	        	sqlCommand.append( column[indexSKU].replace("'", "\\'") );
	        	sqlCommand.append(" ') ,");
	        	
	        	listArg.clear();
	        	listArg.add(column[indexSKU].replace("'", "\\'"));
	        	listArg.add(username);
	        	
	        	ResultSet rs = dataSource.executeBateRS(MergeFileConstants.FINDPRODUCTENTITYSOMECOLUMN, listArg);
	        	if(rs.next()){
	        		mapRow.put(MergeFileConstants.PRICE, rs.getString(MergeFileConstants.PRICE));
	        		mapRow.put(MergeFileConstants.MSRP, rs.getString(MergeFileConstants.MSRP));
	        		mapRow.put(MergeFileConstants.MIN_PRICE, rs.getString(MergeFileConstants.MIN_PRICE));
	        	}
	        	
	        	writeFile(mapRow,true);
	        	
	        }
	        sqlCommand.setLength(sqlCommand.length() - 1);
	        dataSource.executeBate(sqlCommand.toString());
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
	}
	

	public void generateFile(){
		
		try{
			dataSource = new DataSource();
			dataSource.getConnect();
			List<Map<String,String>> listMap = dataSource.findUser();
			
			
			String filename;
			for(Map<String, String> map : listMap){
				
				filename = MergeFileConstants.PATTERNFILE.concat(map.get(MergeFileConstants.USERCODE)).concat(MergeFileConstants.TXT_TYPE);
				createFile(filename);
				readBaseFile(map.get(MergeFileConstants.USERNAME));
				Map<String,Map<String,String>> customerEntity = dataSource.findCustomerEntity(map.get(MergeFileConstants.USERNAME));
				if(customerEntity.size() > 0){
					findProductSpect(customerEntity,map.get(MergeFileConstants.USERNAME));
				}
				closeFile();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			dataSource.closeConnect();
			closeFile();
		}
		

	}
	
	private void createFile(String filename) throws Exception{
		
			writer = new FileWriter(System.getProperty("pOutput")+"\\"+filename);
			buffer = new BufferedWriter(writer);
	}
	
	private void closeFile(){
		try{if(buffer != null)buffer.close();}catch(Exception e){}
		try{if(writer != null)writer.close();}catch(Exception e){}
		try{if(br != null)br.close();}catch(Exception e){}
	}
	
	private void writeFile(Map<String,String> data , boolean newLine) throws Exception{
		try {
			str.setLength(0);
			for(String head : listHeader){
				str.append("\"");
				str.append(data.get(head) == null?"":data.get(head));
				str.append("\"");
				str.append(",");
			}
			str.setLength(str.length()-1);
			if(newLine){
				buffer.newLine();
			}
			buffer.write(str.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}		
	}
	
	private void findProductSpect(Map<String,Map<String,String>> customerEntity,String userName) throws Exception{
		
		try{
			List<String> listArg = new ArrayList<>();
			Map<String,String> map ;
			
			for(String sku : customerEntity.keySet()){
				listArg.clear();
				map = customerEntity.get(sku);
				listArg.add(sku.replace("'", "\\'"));
				listArg.add(userName);
				dataSource.findProductSpec(map, listArg);
				writeFile(map,true);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
	}

}
